package name.huzhenbo.java.klass;

import java.util.Collection;
import java.util.HashSet;

/**
 * Effective Java, item 16, favor composition over inheritance
 * <p/>
 * Inheriting from ordinary concrete classes across package boundaries,
 * however, is dangerous.
 * <p/>
 * Inheritance is appropriate only in circumstances where the subclass really is a
 * subtype of the superclass.
 * <p/>
 * Unlike method invocation, inheritance violates encapsulation [Snyder86].
 * In other words, a subclass depends on the implementation details of its superclass
 * for its proper function.  (Inheritance build up a couppled relationship between superclass and subclass)
 * <p/>
 * To summarize, inheritance is powerful, but it is problematic because it
 * violates encapsulation. It is appropriate only when a genuine subtype relationship
 * exists between the subclass and the superclass. Even then, inheritance may lead to
 * fragility if the subclass is in a different package from the superclass and the
 * superclass is not designed for inheritance. To avoid this fragility, use composition
 * and forwarding instead of inheritance, especially if an appropriate interface to
 * implement a wrapper class exists. Not only are wrapper classes more robust than
 * subclasses, they are also more powerful.
 */
class InstrumentedHashSet<E> extends HashSet<E> {
    private int count;

    public int getCount() {
        return count;
    }

    @Override
    public boolean add(E e) {
        count++;
        return super.add(e);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        count += c.size();
        // wrong, addAll is implemented based on add.
        return super.addAll(c);
    }
}
